import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lenovo
 * Date: 2022-12-16
 * Time: 13:43
 */
@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    //json格式
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    //doGet方法在前端获取blog_List和blog_detail时都要用到,使用有无query string来区别
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json ; charset=utf8");
        //数据操作接口
        BlogDao blogDao = new BlogDao();
        //判断是否有query string
        String blogId = req.getParameter("blogId");
        if(blogId == null){//blog_list发来的get请求
            List<Blog> blogs = blogDao.selectAll();
            resp.getWriter().write(objectMapper.writeValueAsString(blogs));
        }else{//blog_detail发来的请求
            Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
            resp.getWriter().write(objectMapper.writeValueAsString(blog));

        }




    }


    //提交博客
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.通过session来获取当前登录用户的userID
        HttpSession session = req.getSession(false);
        if(session == null){
            resp.setStatus(403);
            resp.setContentType("text/html ;charset=utf8");
            resp.getWriter().write("未登入");
            return;
        }
        User user = (User)session.getAttribute("user" );
        if (user == null){
            resp.setStatus(403);
            resp.setContentType("text/html ;charset=utf8");
            resp.getWriter().write("未登入");
            return;
        }
        //获取到query string里的内容
        //给req设置字符集,防止获取的参数有误
        req.setCharacterEncoding("utf8");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        //blogId是自增主键,postTime用now()函数,在sql里就已经处理好了
        //2.将博客插入到数据库里
        BlogDao blogDao = new BlogDao();
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUserId());
        blogDao.insert(blog);
        //3.重定向到博客列表页
        resp.sendRedirect("blog_list.html");

    }
}
